<template>
  <div>
    <div ref="editor" style="text-align:left;width:790px;overflow-x: hidden;" v-if="defaultType==='place'">
     <p><img src="static/images/rich_image_1@2x.png" alt="rich_1" style="" width="100" height="20"></p>
     <p>对场地的位置进行详细的说明</p>
      <p><img src="static/images/rich_image_2@2x.png" alt="rich_2" style="" width="100" height="20"></p>
      <p>对场地的地形地貌进行详细的说明，以便其他的车友来玩</p>
      <p><img src="static/images/rich_image_3@2x.png" alt="rich_3" style="" width="100" height="20"></p>
      <p>4颗星</p>
      <p><img src="static/images/rich_image_4@2x.png" alt="rich_4" style="" width="100" height="20"></p>
      <p>越野,四驱SUV</p>
      <p><img src="static/images/rich_image_5@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>对场地玩法进行介绍</p>
    </div>
    <div ref="editor" style="text-align:left;width:790px;overflow-x: hidden;" v-else>
      <p><img src="static/images/rich_image_6@2x.png" alt="rich_1" style="" width="100" height="20"></p>
      <p>对本次活动进行简单介绍</p>
      <p><img src="static/images/rich_image_7@2x.png" alt="rich_2" style="" width="100" height="20"></p>
      <p>活动难度 : 3颗星</p>
      <p><img src="static/images/rich_image_8@2x.png" alt="rich_3" style="" width="100" height="20"></p>
      <p>详细的活动行程安排</p>
      <p><img src="static/images/rich_image_9@2x.png" alt="rich_4" style="" width="100" height="20"></p>
      <p>关键景点介绍</p>
      <p><img src="static/images/rich_image_10@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>报名截止时间,天气预报,备用路线,参考攻略,额外事项等(可选择补充)</p>
      <p><img src="static/images/rich_image_11@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>1. 登山鞋或军胶(必备)、登山杖、雨具(必备)、头灯/电筒(必备)、手套、垃圾袋、防晒帽、防晒油、手机（带好充电宝）。</p>
      <p> 2. 药品（蛇药、十滴水、藿香正气口服液、云南白药、创可贴等）及自己需要的特殊物品。</p>
      <p> 3. 午餐（自带）、2升以上饮用水+1升的运动饮料，可带少量榨菜、瓜果、奶糖、牛肉干等零食</p>
      <p><img src="static/images/rich_image_12@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>对讲机,GPS,工具箱,公共药包等</p>
      <p><img src="static/images/rich_image_13@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>1、报名前了解本次活动强度、危险程度，结合自身情况决定是否参与。</p>
      <p>2、确保自己身体健康，状态良好，也没有罹患不适合剧烈户外运动的疾病。</p>
      <p>3、出发前一天晚上休息充分，没有大量饮酒，也没有其他可能影响良好体能、判断能力的行为。</p>
      <p>4、出发前请确认已购买保险，将活动信息和领队联系方式留给紧急联系人。</p>
      <p>5、携带合适的装备和足够的水粮，自力更生。</p>
      <p>6、自备垃圾袋将活动中产生的垃圾全部带下山。</p>
      <p>7、在整个户外活动过程中接受领队的协调配合，不脱离队伍独自行动、不从事其他可能给自己和他人带来危险的举动。</p>
      <p>8、一旦自己发生身体不适和其他危险，能够在第一时间通知领队和协作，以获得他们的指导和帮助，并配合他们采取必要的避险、治疗措施。</p>
      <p><img src="static/images/rich_image_14@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>1、高原反应：准备红景天等抗高原反应的药物；</p>
      <p>2、冻伤、感冒：充足准备保暖的装备及常用药品；</p>
      <p>3、失温：领队把控好队伍行进的节奏，有规律地停留休息，补充能量，防止队员体力透支；</p>
      <p>4、晒伤、中暑：出行前做好防晒工作（擦防晒霜），携带充足的饮用水，备好防暑药品；</p>
      <p>5、滑坠山崖、谷沟：领队在通过有滑坠风险的路段时及时提醒，队员统一听从指挥，不擅自行动；</p>
      <p>6、被乱石或树木滚落击中：遇到有山体滑落风险的路段，行进队伍的间距要拉开，所有队友随时观察山体变化，遇到危险大声提醒队友躲开；</p>
      <p>7、滑倒、摔伤、扭伤：行走高低不平的地面时，领队提醒队员注意安全，队友之间相互协作；</p>
      <p>8、毒蛇、黄蜂侵扰：在穿越草丛树林时，绑好裤脚，穿好鞋袜，遇到蜂类，最好站着不动，让它自行飞过去;</p>
      <p>9、被人打劫：结伴而行，不掉队，不单独行动;</p>
      <p>10、山洪、雷击、山火：观察天气征兆，不在暴雨或暴雨过后的溪谷逗留；雷雨天气不在大树、高处、岩石下停留躲避；若发现山火，往植物密度少的地方逃跑;</p>
      <p>11、溺水，被溪水冲走：在渡河前，先观察水流情况判断横渡点的安全性，渡河前做好保护措施;</p>
      <p><img src="static/images/rich_image_15@2x.png" alt="rich_5" style="" width="100" height="20"></p>
      <p>一、 本人系具备完全民事行为能力的成年人，自愿参加此次活动，自由结合，组队前往，该团队和越野侠活动平台并无组织、委派等其他任何法律关系；团队中各成员均处于平等地位，所作分工仅仅为了发挥各自优势，并无上下级或者指挥与被指挥关系。</p>
      <p>二、 本人已经充分了解活动过程中可能面临的风险，包括但不限于迷路、跌坠、山洪、泥石流、落石、雷电、涉水、中暑失温及冻伤、中毒、疾病、动物袭击、山火、捕兽器具伤害、天气异常、第三人带来的伤害、交通意外…外力所致和自身原因所导致的其他风险等等。出发前，本人已经了解、掌握了面临可能发生的危险时应该采取的减轻和避免伤害的措施。</p>
      <p>三、 活动过程中遇到危险，相信团队中其他所有成员均会尽力救助，但即使如此仍不能完全避免伤害的产生时，声明人不向其他成员主张任何赔偿责任，除非该伤害是由于其他成员的故意所导致。</p>
      <p>四、本人已经仔细阅读、完全理解和认同本声明</p>
    </div>
  </div>
</template>
<script>
import E from 'wangeditor'
import axios from 'axios'
import aliUtil from '../assets/aliUtil'

export default {
  name: 'editor',
  props:{
    jsonDescription:String,
    type:String
  },
  data () {
    return {
      editorContent: '',
      jsonArr: [],
      myJsonDescription:this.jsonDescription,
      defaultType:this.type
    }
  },
  methods: {
    getText(argument) {
      let DivEle = document.createElement("div");
      for (let i = 0; i < argument.length; i++) {
        let Item = argument[i];
        if (i >= 1 && Item['title'] =="\n" && argument[i-1]['title'] != "\n"){
          let brNode = document.createElement("br");
          DivEle.appendChild(brNode);
        }
        if (Item['title'] && Item['title'] !=='\n'){
          let pEle = document.createElement("p");
          let textNode = document.createTextNode(Item['title']);
          pEle.appendChild(textNode);
          if(Item['bold'] === 1){
            pEle.style.fontWeight = "bold";
          }
          if(Item['font'] === 1){
            pEle.style.fontSize = Item['font']+"px";
          }
          if(Item['obliq'] === 1){
            pEle.style.fontStyle = "oblique";
          }
          if(Item['underline'] === 1){
            pEle.style.textDecoration = "underline";
          }
          if(Item['color']){
            pEle.style.color = Item['color'];
          }
          pEle.style.lineHeight = '30px';
          pEle.style.display = 'inline';
          DivEle.appendChild(pEle);
        }
        if(Item['img']){
          let ImgEle = document.createElement("img");
          ImgEle.setAttribute("src", Item['img']);
          DivEle.appendChild(ImgEle);
        }
        if(Item['locImg']){
          let ImgEle = document.createElement("img");
          let imgSrc = 'static/images/rich_image_'+Item["locImg"]+'@2x.png';
          ImgEle.setAttribute("src", imgSrc);
          ImgEle.style.width = '100px';
          ImgEle.style.height= '20px';
          DivEle.appendChild(ImgEle);
        }
      }
      return DivEle;
    },
    myFormat (json) {
      let that = this
      for (let i = 0, j = json.length; i < j; i++) {
        let item = json[i]
        let tag = item['tag']
        let attrs = item['attrs']
        let children = item['children']
        if (tag === 'p' || tag === 'div') {
          let oBr = {
            title : "\n"
          }
          if (that.jsonArr.length >= 1 && that.jsonArr[that.jsonArr.length - 1]['title'] !== "\n"){
            that.jsonArr.push(oBr)
          }
          that.myFormat(children)
          that.jsonArr.push(oBr)
        } else if (tag === 'span' && children.length === 1) {
          if (children[0]['tag'] === 'br') {
            let oBr = {
              title : "\n"
            }
            that.jsonArr.push(oBr)
            return false
          }
          let fontSize = that.getStyle(attrs[0]['value'], 'font-size')
          switch (fontSize) {
            case ' x-small':
              fontSize = 13
              break
            case ' small':
              fontSize = 15
              break
            case ' normal':
              fontSize = 17
              break
            case ' large':
              fontSize = 19
              break
            default:
              fontSize = 15
              break
          }
          let oText = {
            'title': children[0].toString(),
            'bold': (that.getStyle(attrs[0]['value'], 'font-weight')) ? 1 : 0,
            'font': fontSize,
            'obliq': (that.getStyle(attrs[0]['value'], 'font-style')) ? 1 : 0,
            'underline': (that.getStyle(attrs[0]['value'], 'text-decoration-line')) ? 1 : 0,
            'color': (that.getStyle(attrs[0]['value'], 'color')) ? that.colorRGB2Hex(that.getStyle(attrs[0]['value'], 'color')) : '#000000'
          }
          that.jsonArr.push(oText)
        } else if (tag === 'span' && children.length !== 1) {
          let fontSize = that.getStyle(attrs[0]['value'], 'font-size')
          switch (fontSize) {
            case ' x-small':
              fontSize = 13
              break
            case ' small':
              fontSize = 15
              break
            case ' normal':
              fontSize = 17
              break
            case ' large':
              fontSize = 19
              break
            default:
              fontSize = 15
              break
          }
          let oText = {
            'title': children[0].toString(),
            'bold': (that.getStyle(attrs[0]['value'], 'font-weight')) ? 1 : 0,
            'font': fontSize,
            'obliq': (that.getStyle(attrs[0]['value'], 'font-style')) ? 1 : 0,
            'underline': (that.getStyle(attrs[0]['value'], 'text-decoration-line')) ? 1 : 0,
            'color': (that.getStyle(attrs[0]['value'], 'color')) ? that.colorRGB2Hex(that.getStyle(attrs[0]['value'], 'color')) : '#000000'
          }
          that.jsonArr.push(oText)
          that.getChildren(children[1])
        } else if (tag === 'img') {
          let oImg = {}
          for (let i = 0, j = attrs.length; i < j; i++) {
            if (attrs[i]['name'] === 'src') {
              if(attrs[i]['value'].substring(0, 5) === 'https'){
                oImg.img = attrs[i]['value']
              }else{
                let attrIndex = attrs[i]['value'].split('/').length - 1;
                let imgName = attrs[i]['value'].split('/')[attrIndex];
                let imgNum = imgName.split("@")[0];
                let imgNumArr = imgNum.split("_");
                let myNum = imgNumArr[imgNumArr.length - 1];
                oImg.locImg = myNum;
              }
            } else if(attrs[i]['name'] === 'style' && attrs[i]['value'] !== ""){
              oImg.imgW = parseInt(that.getStyle(attrs[i]['value'], 'width'))
              oImg.imgH = parseInt(that.getStyle(attrs[i]['value'], 'height'))
            }else{
              oImg.imgW = 100
              oImg.imgH = 20
            }
          }
          that.jsonArr.push(oImg)
        } else if (tag === 'br') {
          let oBr = {
            title : "\n"
          }
          that.jsonArr.push(oBr)
        }else{
          let oText = {
            'title': item
          }
          that.jsonArr.push(oText)
        }
      }
    },
    // 递归children
    getChildren (children) {
      let that = this
      let attrs = children['attrs']
      let child = children['children']
      if (child.length === 1) {
        let fontSize = that.getStyle(attrs[0]['value'], 'font-size')
        switch (fontSize) {
          case ' x-small':
            fontSize = 13
            break
          case ' small':
            fontSize = 15
            break
          case ' normal':
            fontSize = 17
            break
          case ' large':
            fontSize = 19
            break
          default:
            fontSize = 15
            break
        }
        let oText = {
          'title': child[0].toString(),
          'bold': (that.getStyle(attrs[0]['value'], 'font-weight')) ? 1 : 0,
          'font': fontSize,
          'obliq': (that.getStyle(attrs[0]['value'], 'font-style')) ? 1 : 0,
          'underline': (that.getStyle(attrs[0]['value'], 'text-decoration-line')) ? 1 : 0,
          'color': (that.getStyle(attrs[0]['value'], 'color')) ? that.colorRGB2Hex(that.getStyle(attrs[0]['value'], 'color')) : '#000000'
        }
        that.jsonArr.push(oText)
      } else {
        that.getChildren(child[1])
      }
    },
    getStyle (attrs, attr) {
      let attrsArr = attrs.split(';')
      let attrsNewArr = {}
      for (let i = 0, j = attrsArr.length - 1; i < j; i++) {
        let item = attrsArr[i].trim()
        let itemArr = item.split(':')
        attrsNewArr[itemArr[0]] = itemArr[1]
      }
      return attrsNewArr[attr]
    },
    colorRGB2Hex (color) {
      let rgb = color.split(',')
      let r = parseInt(rgb[0].split('(')[1])
      let g = parseInt(rgb[1])
      let b = parseInt(rgb[2].split(')')[0])
      let hexColor = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
      return hexColor
    },
    uploadThumbImg (blob, callback) {
      aliUtil.canvasDataURL(blob, function (value) {
        let base64 = value.split(',')[1].replace(/\s/g, '');
        let fileType = value.split(';')[0].split(':')[1];
        let newBlob = aliUtil.toBlob(base64, fileType);
        let Form = new FormData()
        Form.append('content', newBlob)
        Form.append('token', localStorage.getItem('token'))
        Form.append('type', 0)
        Form.append('clientType', 'pc')
        let config = {
          headers: {
            'client': 'pc',
            'Content-Type': 'multipart/form-data;charset=utf-8'
          }
        }
        axios.post('/Upload/UploadImg', Form, config).then(function (response) {
          if (response.status === 200) {
            callback(response['data']['data'])
          }
        })
      });
    }
  },
  mounted () {
    let that = this
    this.editor = new E(this.$refs.editor)
    this.editor.customConfig.onchange = (html) => {
      this.editorContent = html
    }
    // 自定义菜单配置
    this.editor.customConfig.menus = [
      'fontSize',
      'bold',
      'italic',
      'underline',
      'foreColor',
      'image'
    ]
    this.editor.customConfig.colors = [
      '#000000',
      '#F79E20',
      '#EF4F3E',
      '#4CCE92',
      '#FFCC00',
      '#4A9CD5'
    ]
    this.editor.customConfig.zIndex = 1
    this.editor.customConfig.showLinkImg = false
    this.editor.customConfig.pasteIgnoreImg = true
    this.editor.customConfig.customUploadImg = function (files, insert) {
      if (files.length === 0) {
        return false
      } else {
        files.map(file => {
          that.uploadThumbImg(file, function (res) {
            insert(res[0]['url'])
          })
        })
      }
    }
    this.editor.customConfig.pasteTextHandle = function (content) {
      let regHtml = /<[^<>]+>/g
      let regStyle = /<style>(\S*)<\/style>/g
      var regTrim = /\s+/g
      let str = content.replace(regTrim, '').replace(regStyle, '').replace(regHtml, '')
      return str
    }
    this.editor.customConfig.onchange = function () {
      that.jsonArr = []
      let json = that.editor.txt.getJSON()
      that.myFormat(json)
      that.$nextTick(function () {
        that.$emit("jsonDetail", {jsonStr:JSON.stringify(that.jsonArr)})
      })
    }
    this.editor.create();
    this.$nextTick(function () {
      let that = this;
      if(that.myJsonDescription !== ""){
        let arr = JSON.parse(that.myJsonDescription);
        let htmlStr = that.getText(arr).innerHTML;
        that.editor.txt.html(htmlStr);
      }
    })
  }
}
</script>

<style scoped>
</style>
